package com.sz.app.oss.api.common.customer;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.utils.StringUtils;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xutao on 17/3/29.
 */
@RestController
@RequestMapping("${api}/customer/user")
@Api(description = " ", tags = "037-002、客户信息管理-子账号")
public class CusUserController extends BaseController {

    @Autowired
    private CustomerUserService customerUserService;

    /**
     * 获取用户账号列表
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "搜索客户账号", notes = "搜索用户，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "refCustomerId", value = "客户关联id",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public QResultDto getUser(@RequestParam(defaultValue = "") String q,
                              @RequestParam(defaultValue = "userName") String sortName,
                              @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                              @RequestParam(defaultValue = "1") int pageIndex,
                              @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                              @RequestParam int refCustomerId) throws BizException {

        return customerUserService.findCustomerList(q, pageIndex, pageSize, sortName, isAsc, null, refCustomerId);
    }

    /**
     * 新建一个用户账号
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "新建客户账号", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public ResultDto saveUser(@RequestBody @Validated CusUser cusUser) throws Exception {

        int userId = customerUserService.save(cusUser);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.MODULE_CUSTOMER_ADD_SUBACCOUNT_SUCCESS);
        dto.setData(userId);
        return dto;
    }

    /**
     * 修改一个账号
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "修改客户账号", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "", method = {RequestMethod.PUT})
    public ResultDto updateUser(@RequestBody @Validated CusUser cusUser) throws Exception {
        List<CusUser> cusUserList = new ArrayList<CusUser>();
        cusUserList.add(cusUser);
        customerUserService.updateCustomer(cusUserList);
        ResultDto dto = getUpdateSuccessDto(MessagesCodes.MODULE_CUSTOMER_USER_ACCOUNT);
        dto.setData(cusUser.getId());
        return dto;
    }

    /**
     * 删除一个账号 非物理删除 打标志 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "删除一个客户账号", notes = "非物理删除 打标志 不允许登录<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "客户账号的id ", required = true, dataType = "int", paramType = "path")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    public ResultDto deleteUser(@PathVariable int id) throws Exception {

        List<Integer> ids = new ArrayList<Integer>();

        ids.add(id);

        customerUserService.batchDelete(ids);

        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_CUSTOMER_SUBACCOUNT);

        dto.setData(id);

        return dto;
    }

    /**
     * 批量删除客户账号 非物理删除 打标志 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "批量删除客户账号", notes = "非物理删除 打标志 不允许登录<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "客户账号的ids",
                    required = true, dataType = "string", paramType = "body")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    public ResultDto deleteUser(@RequestBody List<Integer> ids) throws Exception {

        customerUserService.batchDelete(ids);
        return getDeleteSuccessDto(MessagesCodes.MODULE_CUSTOMER_SUBACCOUNT);
    }

    /**
     * 锁定客户账号 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "锁定客户账号", notes = "不允许登录<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/lock", method = {RequestMethod.POST})
    public ResultDto lockUser(@ApiParam(value = "客户账号的ids", required = true) @RequestBody List<Integer> ids)
            throws Exception {
        customerUserService.lockCustomer(ids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.CUSTOMER_LOCK_SUCCESS);
        dto.setData(ids);
        return dto;
    }

    /**
     * 解锁客户账号
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "解锁定客户账号", notes = "允许登录<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/unlock", method = {RequestMethod.POST})
    public ResultDto unLockUser(@RequestBody List<Integer> ids) throws Exception {
        customerUserService.unlockCustomer(ids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.CUSTOMER_UNLOCK_SUCCESS);
        dto.setData(ids);
        return dto;
    }

    /**
     * 异步校验邮箱
     */
    @ApiOperation(value = "异步校验邮箱", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "邮箱",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "账号id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/checkemail", method = {RequestMethod.GET})
    public ResultDto userEmailCheck(@RequestParam String email,
                                    @RequestParam(required = false, defaultValue = "0") int userId) {

        customerUserService.customerEmailCheck(userId, email);
        return new ResultDto();
    }

    /**
     * 异步校验用户名称
     */
    @ApiOperation(value = "异步校验用户名称", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "账号id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/checkusername", method = {RequestMethod.GET})
    public ResultDto userUserNameCheck(@RequestParam String userName,
                                       @RequestParam(required = false, defaultValue = "0") int userId) {

        customerUserService.customerUserNameCheck(userId, userName);

        return new ResultDto();
    }

    /**
     * 异步校验手机号码
     */
    @ApiOperation(value = "异步校验手机号码", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobilePhone", value = "手机号码",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "账号id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/checkmobilephone", method = {RequestMethod.GET})
    public ResultDto checkMobilePhoneExist(@RequestParam String mobilePhone,
                                       @RequestParam(required = false, defaultValue = "0") int userId) {

        boolean exist = customerUserService.checkMobilePhoneExist(userId,mobilePhone);
        ResultDto result = new ResultDto(exist);
        return result;
    }

    /**
     * 改变客户账号密码
     */
    @ApiOperation(value = "更改客户账号密码", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "客户账号的id ",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "oldPassword", value = "旧密码",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "newPassword", value = "新密码",
                    required = true, dataType = "string", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/updatepassword/{id}", method = {RequestMethod.PUT})
    public ResultDto changePassword(@PathVariable int id,
                                    @RequestParam String oldPassword,
                                    @RequestParam String newPassword) {
        customerUserService.changeCustomerPassword(id, oldPassword, newPassword);
        return new ResultDto();
    }

    /**
     * 重置客户账号密码
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "重置客户账号密码", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/resetpasswd", method = {RequestMethod.POST})
    public ResultDto resetpasswd(
            @ApiParam(value = "账号ids", required = true) @RequestBody List<Integer> userids) throws Exception {

        customerUserService.resetUsersPasswd(userids);

        ResultDto dto = getOperateSuccessDto(MessagesCodes.USER_RESET_PASSWORD_SUCCESS);

        dto.setData(userids);

        return dto;
    }

    /**
     * 凭借主账号Id查询子账号信息
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "凭借主账号Id查询子账号信息", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " + Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerid", value = "customerId", dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "S", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", dataType = "int",
                    paramType = "query")
    })
    @RequestMapping(value = "/getbycustomer/{customerid}", method = {RequestMethod.GET})
    public QResultDto findUserByCustomerId(@PathVariable int customerid,
                                           @RequestParam(defaultValue = "") String q,
                                           @RequestParam(required = false) Integer pageIndex,
                                           @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws Exception {
        QResultDto qResultDto = new QResultDto();
        if (pageIndex == null) {
            List<CusUser> cusUserList = customerUserService.findByCustomerId(customerid);
            qResultDto.setData(cusUserList);
        }
        else {
            qResultDto = customerUserService.findSubAccountByLoginId(customerid, q, pageIndex, pageSize);
        }
        return qResultDto;
    }

    /**
     * 凭借子账号Id查询子账号信息
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "凭借子账号Id查询子账号信息", notes = "-<br>权限："  +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public QResultDto findUserById(@PathVariable int id) throws Exception {

        CusUser cusUser = customerUserService.findById(id);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(cusUser);

        return qResultDto;
    }

    /**
     * 获取username列表
     */
    @ApiOperation(value = "获取用户名列表", notes = "获取用户名列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "客户类型：1是物流，2是贸易， 3两者都是",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/usernamelist", method = {RequestMethod.GET})
    public QResultDto getUserNameList(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "userName") String sortName,
                                      @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                      @RequestParam(name = "userType", defaultValue = "1") int userType) throws BizException {
        q= StringUtils.replaceSqlPattern(q);
        return customerUserService.getUserNameList(q, pageIndex, pageSize, sortName, isAsc, null, userType);
    }

    /**
     * 获取fullname列表
     */
    @ApiOperation(value = "获取fullname列表", notes = "获取fullname列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/fullnamelist", method = {RequestMethod.GET})
    public QResultDto getFullNameList(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "userName") String sortName,
                                      @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws BizException {
        q= StringUtils.replaceSqlPattern(q);
        return customerUserService.getFullNameList(q, pageIndex, pageSize, sortName, isAsc, null);
    }

    /**
     * 获取主账号列表
     */
    @ApiOperation(value = "获取主账号列表", notes = "获取主账号列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/primaryaccountlist", method = {RequestMethod.GET})
    public QResultDto getPrimaryAccountList(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "userName") String sortName,
                                      @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws BizException {
        q= StringUtils.replaceSqlPattern(q);
        return customerUserService.getPrimaryAccountListPage(q, pageIndex, pageSize, sortName, isAsc, null);
    }

    /**
     *
     * 查找用户对应的货币信息
     */
    @ApiOperation(value = "查找用户对应的货币信息", notes = "-<br>权限：NONE")
    @RequestMapping(value = "/getcoin/{userid}", method = {RequestMethod.GET})
    public QResultDto getTradingCurrencyByUserId(@PathVariable int userid) {

        return customerUserService.getTradingCurencyByUserId(userid);
    }

    /**
     * 获取username列表-为了支持二级联动
     */
    @ApiOperation(value = "获取username列表-为了支持二级联动", notes = "获取用户名列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "客户类型：1是物流，2是贸易， 3两者都是",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "refCustomerId", value = "关联的账户ID",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/likedusernamelist", method = {RequestMethod.GET})
    public QResultDto getLinkedUserNameList(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "userName") String sortName,
                                      @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                      @RequestParam(name = "userType", defaultValue = "1") int userType,
                                      @RequestParam(name = "refCustomerId", defaultValue = "0") int refCustomerId)
            throws BizException {

        q= StringUtils.replaceSqlPattern(q);

        return customerUserService.getLinkedUserNameList(q, pageIndex, pageSize, sortName,
                isAsc, null, userType, refCustomerId);
    }

}
